const path=require('path');
const fs= require('fs');

//初始化方法
function initScript(url){
    url=(function get_url(url){
        if(chrome.extension){
            return /(http[s]:\/\/)|(\/\/)/.test(url)?url:chrome.extension.getURL(url);
        }
        return url;
    })(url);
    return fetch(url).then(e=>e.text()).then(e=>window.eval(e));
}
//初始化vue
function PageLoadVue(App){
    let Vue=require('vue').default;
    let $=require('jquery');
    try{
        let vm=new Vue(App).$mount();
        $('body').append(vm.$el);
    }catch (e) {
        console.error(e)
    }
}
//webpack创建输出文件
function pkCreatedFile(fileName,fileStr){
    this.assets[fileName] = {
        source: function() {
            return fileStr;
        },
        size: function() {
            return fileStr.length;
        }
    };
}
function HomePath(filePath){
    return path.join(process.env.INIT_CWD,filePath);
}
//删除文件和文件夹
function deleteFile(path) {
    let deleteall=constructor;
    let files = [];
    if(fs.existsSync(path)) {
        if(fs.statSync(path).isDirectory()){
            files = fs.readdirSync(path);
            files.forEach(function(file, index) {
                let curPath = path + "/" + file;
                if(fs.statSync(curPath).isDirectory()) { // recurse
                    deleteall(curPath);
                } else { // delete file
                    fs.unlinkSync(curPath);
                }
            });
            fs.rmdirSync(path);
        }else{
            fs.unlinkSync(path);
        }
    }
}
function getFileType(filePath){
    let startIndex = filePath.lastIndexOf(".");
    if(startIndex != -1)
        return filePath.substring(startIndex+1, filePath.length).toLowerCase();
    else
        return "";
}
module.exports={
    initScript(url){
        return `(${initScript.toString()})(${JSON.stringify(url)})`;
    },
    initVue(url){
        return `(${PageLoadVue.toString()})(${JSON.stringify(url)})`;
    },
    pkCreatedFile,HomePath,deleteFile,getFileType
};
